﻿namespace ChinaUnicom.Parser.Parsers
{
    using System.Linq;
    using ChinaUnicom.Models;
    using HtmlAgilityPack;

    internal class FeeHistoryParser : IItemsParser
    {
        public ItemType Type
        {
            get { return ItemType.FeeHistory; }
        }

        public ItemCollection Parse(string html)
        {
            ItemCollection items = new ItemCollection();

            HtmlDocument doc = new HtmlDocument();
            doc.LoadHtml(html.Replace("&nbsp;", string.Empty));

            HtmlNode div = doc.DocumentNode.Descendants("div")
                .Where(x => x.Attributes["class"] != null && x.Attributes["class"].Value == "nrong")
                .FirstOrDefault();

            if (div != null)
            {
                HtmlNode contentContainer = div.Descendants("div")
                    .Where(x => x.Attributes["class"] != null && x.Attributes["class"].Value == "mrlf2")
                    .FirstOrDefault();

                if (contentContainer != null)
                {
                    foreach (HtmlNode node in contentContainer.ChildNodes)
                    {
                        if (node.Name == "#text")
                        {
                            string text = node.InnerText.InnerTextTrim();
                            string[] values = text.Split(new[] { ':' });

                            // key:value
                            if (values.Length == 2)
                            {
                                Item item = new Item();
                                item.Name = values[0].InnerValueTrim();
                                item.Value = values[1].InnerValueTrim();
                                items.Add(item);
                            }
                        }
                    }
                }
            }

            return items;
        }
    }
}
